package com.xyd.wechat.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xyd.wechat.common.ApplicationConfig;
import com.xyd.wechat.common.Constant;
import com.xyd.wechat.mapper.ChatRobotRecordMapper;
import com.xyd.wechat.mapper.ChatRobotUserMapper;
import com.xyd.wechat.model.ChatRobotRecord;
import com.xyd.wechat.model.ChatRobotUser;
import com.xyd.wechat.service.AutoReplyService;
import com.xyd.wechat.service.CustomerService;
import com.xyd.wechat.vo.Message;
import com.xyd.wechat.vo.ResultVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Calendar;

@Service
public class AutoReplyServiceImpl implements AutoReplyService {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ApplicationConfig applicationConfig;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private ChatRobotUserMapper chatRobotUserMapper;

    @Autowired
    private ChatRobotRecordMapper chatRobotRecordMapper;

    @Autowired
    private CustomerService customerService;

    /**
     * 微信公众号输入关键字，机器人根据关键字自动回复
     *
     * @param message
     * @return
     */
    @Override
    public Message autoReplyByRobot(Message message) {
        ChatRobotUser user = null;
        ChatRobotRecord chatRobotRecord = new ChatRobotRecord();
        chatRobotRecord.setKeywords(message.getContent());
        try {
            // 判断用户已经转人工，后续机器人不在对该用户自动回复
            ChatRobotUser chatRobotUser = new ChatRobotUser();
            chatRobotUser.setUsername(message.getToUserName());
            chatRobotUser.setSource(Constant.SOURCE_WX);
            user = chatRobotUserMapper.selectOne(chatRobotUser);
            if (user == null) {
                chatRobotUser.setStatus(Constant.Y);
                chatRobotUser.setCreatetime(Calendar.getInstance().getTime());
                chatRobotUserMapper.insertUseGeneratedKeys(chatRobotUser);
                user = chatRobotUser;
            } else {
                if (applicationConfig.getRobotReply().equals(message.getContent())) {
                    user.setStatus(Constant.Y);
                    user.setUpdatetime(Calendar.getInstance().getTime());
                    chatRobotUserMapper.updateByPrimaryKey(user);
                    //关闭客服会话，转入智能客服（聊天机器人）
                    if (Constant.SOURCE_WX.equals(message.getSource())) {
                        customerService.closeDialogue(message);
                    }
                }
                if (Constant.N.equals(user.getStatus())) {
                    return null;
                }
            }
            // 根据关键字请求机器人接口，得到返回内容
            String url = String.format("%s?keyword=%s", applicationConfig.getRobotUrl(), message.getContent());
            logger.info("请求机器人：{}", url);
            ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
            //{"code":"0","message":"调用成功","errors":null,"data":{"data":"机器人响应返回内容"}}
            String rsJson = responseEntity.getBody();
            logger.info("机器人响应内容：{}", rsJson);
            if (rsJson == null || rsJson.length() == 0) {
                return null;
            }
            ResultVo resultVo = objectMapper.readValue(rsJson, ResultVo.class);
            if (resultVo != null) {
                if ("0".equals(resultVo.getCode())) {
                    if (resultVo.getData() != null) {
                        if (resultVo.getData().getData() != null) {
                            // 设置返回对象
                            message.setContent(resultVo.getData().getData());
                        } else {
                            logger.info("根据关键字：{},响应内容为空。", message.getContent());
                            message.setContent(applicationConfig.getDefaultReply());
                        }
                    } else {
                        logger.info("根据关键字：{},响应内容为空。", message.getContent());
                        message.setContent(applicationConfig.getDefaultReply());
                    }
                } else {
                    logger.info("根据关键字：{},机器人没有搜索到内容。", message.getContent());
                    message.setContent(applicationConfig.getDefaultReply());
                }
            } else {
                message.setContent(applicationConfig.getDefaultReply());
            }
        } catch (Exception e) {
            logger.error("自动回复发生异常。", e);
            message.setContent(applicationConfig.getDefaultReply());
        }
        // 响应 返回
        try {
            // 如果机器人回复该用户转人工，标记该用户。后续机器人将不在回复此用户信息
            if (applicationConfig.getLabourReply().equals(message.getContent())) {
                user.setStatus(Constant.N);
                user.setUpdatetime(Calendar.getInstance().getTime());
                chatRobotUserMapper.updateByPrimaryKey(user);
                if (Constant.SOURCE_WX.equals(message.getSource())) {
                    // 发送消息给用户
                    customerService.sendToUser(message);
                    // 消息 转人工客服
                    return customerService.transferCustomerService(message);
                }
            }
            message.setSource(null);
            return message;
        } catch (Exception e) {
            logger.error("自动回复（返回结果时）发生异常。", e);
            return null;
        } finally {
            try {
                //记录与机器人的聊天日志
                if (user != null) {
                    chatRobotRecord.setUsername(user.getUsername());
                    chatRobotRecord.setSource(user.getSource());
                    chatRobotRecord.setReply(message.getContent());
                } else {
                    chatRobotRecord.setUsername(message.getFromUserName());
                    chatRobotRecord.setSource(Constant.SOURCE_WX);
                    chatRobotRecord.setReply(message.getContent());
                }
                chatRobotRecordMapper.insertSelective(chatRobotRecord);
            } catch (Exception e) {
                logger.error("数据操作失败", e);
            }
        }
    }
}
